package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.*;
import com.luo.service.ClassService;
import com.luo.service.GoodService;
import com.luo.util.ListTypes;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/1/10 16:11
 */
@WebServlet("/category")
public class TwoClassController extends HttpServlet {

    ClassService classService = new ClassService();
    GoodService goodService = new GoodService();

    @Override
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        //根据id查出一级分类
        OneClass oneClass = classService.queryOneClassByOneId(id);
        //配置一级分类的children
        List<TwoClass> twoClasses = classService.queryTwoClassByOneId(oneClass);
        //配置二级分类的good
        for (TwoClass t :twoClasses) {
            //根据二级的id来查询属于二级的商品
            List<Goods> goods = goodService.queryGoodsByTwoId(String.valueOf(t.getId()));
            //将查询出的结果复制到二级的children中
            List<Object> objList = ListTypes.getObjList(goods);
            t.setGoods(objList);
        }
        //将二级分类的列表转换为Object
        List<Object> objList = ListTypes.getObjList(twoClasses);
        oneClass.setChildren(objList);
        //构造返回的JSON对象
        ResultObj result = new ResultObj();
        result.setCode("1");
        result.setMsg("成功啦");
        result.setResult(oneClass);
        //将对象转为json
        String jsonString = JSON.toJSONString(result);
        //返回到前端
        resp.getWriter().write(jsonString);
        resp.getWriter().close();
    }
}
